<?php
namespace Library;

use Monolog\Logger, Monolog\Handler\StreamHandler;
use Hoa\Registry\Registry;


/**
* Log
*/
class Log {
	//本类单实例变量
	static private $inst = NULL;
	//monolog日志类实例
	private $log = NULL;


	/**
	 * 构造函数
	 * 依赖外部传入参数，用于实例化monolog日志类
	 */
	private function __construct() {
		$conf = Registry::get('conf');
		$chnl = $conf['log']['chnl'];
		$level = $conf['log']['level'];
		$this->log = new Logger($chnl);

		$dir = PRJ_PATH . 'runtime/log/';
		if (!is_dir($dir)) {
			mkdir($dir, 0755, true);
		}
		$this->log->pushHandler(new StreamHandler($dir . $chnl . '_' . date('Ymd') . '.log', $level));
	}


	/**
	 * 获取本类实例
	 */
	static private function getInst() {
		if (null === self::$inst) {
			self::$inst = new self();
		}
		return self::$inst;
	}


	/**
	 * 魔术方法，统一处理静态函数的调用
	 * @param string $method
	 * @param array $args
	 * @throws UnexpectedValueException
	 */
	public static function __callStatic($method, $args) {
		if ( !in_array($method, ['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']) ) {
			throw new UnexpectedValueException("Log level [$method] does not exist!");
		}
		self::getInst()->process($method, $args[0]);
	}


	/**
	 * 调用monolog，写日志
	 * @param string $method
	 * @param mixed $content
	 */
	private function process($method, $content) {
		$realMethod = 'add'.ucfirst($method);
		$content = (String)$content;
		$this->log->$realMethod($content);
	}

}